package umich.max.geolocation.geonames;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
@SuppressWarnings("deprecation")
public class Index {

	private String directory;
	private IndexSearcher index;

	public Index(String directory) {
		this.directory = directory;
	}
	

	public Index(String directory, boolean reading) {
		this.directory = directory;
		if (reading)
			openIndexForReading();
	}


	public void openIndexForReading() {
		try {
			Directory dir = FSDirectory.open(new File(directory));
			IndexReader indexReader = IndexReader.open(dir);
			index = new IndexSearcher(indexReader);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unused")
	public List<Document> getTopNDocs(BooleanQuery query, int numResults) {

		List<Document> matches = new ArrayList<Document>();

		try {
			Analyzer analyzer = new KeywordAnalyzer();
			QueryParser parser = new QueryParser(Version.LUCENE_43, directory,
					analyzer);

			ScoreDoc[] hits = index.search(query, numResults).scoreDocs;
			for (int i = 0; i < hits.length; i++) {
				Document doc = index.doc(hits[i].doc);
				matches.add(doc);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return matches;
	}

	public IndexWriter createIndexWriter() {

		try {
			File indexDirFile = new File(directory);

			Directory dir = FSDirectory.open(indexDirFile);
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_43,
					analyzer);
			iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
			return new IndexWriter(dir, iwc);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}
}
